package com.lihepeng.leecode.interview;

/**
 * 双重校验所单例模式
 * volatile 使用关键字的在于防止指令重排序
 * singleton = new Singleton();
 * 分为三个步骤，分配空间
 * 初始化Singleton
 * singlteon 执行分配的内存空间
 */
public class Singleton {
    private Singleton() {
    }

    private static volatile Singleton singleton = null;

    public static Singleton getInstance() {
        // 校验是为了提高代码执行效率，如果不为空不需要进入同步方法
        if (singleton == null) {
            synchronized (Singleton.class) {
                // 防止二次创建实例，
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }

    private static class SingltonTest implements Runnable {
        @Override
        public void run() {
            Singleton instance = Singleton.getInstance();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(instance);
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            Thread t1 = new Thread(new SingltonTest());
            t1.start();
        }

    }
}
